<template>
  <div class="button_box"> 
    <el-tooltip class="box-item"
        effect="dark"
        content="其他功能"
        placement="left-start"
      >
      <el-button type="" class="button" :icon="Operation" @click="setPanel" circle/></el-tooltip>
      <el-tooltip
        class="box-item"
        effect="dark"
        content="保存"
        placement="left-start"
      ><el-button type="success" @Click="submitData" class="button" :icon="Check" circle /></el-tooltip>
      <el-tooltip
        class="box-item"
        effect="dark"
        content="移除"
        placement="left-start"
      ><el-button type="danger" @Click="removeData" class="button" :icon="Delete" circle /></el-tooltip>
  
  </div>
  <div id="app" class="editor">
    <Editor
      v-model="editorContent"
      api-key="2wmrfbc7a4kqcyqlubtg8iwd2pii4n7oxbq1re22jdu1dtiu"
      output-format="html"
      :init="editorConfig"
    />
  </div>
  <el-drawer v-model="drawer" title="操作面板" :with-header="false" :show-close="false">
    <div>发布者：{{ article.userId }}&nbsp;&nbsp;&nbsp;编号：{{ article.id }}</div>
    <br>
    <div>类型：<el-input v-model="article.type"/></div>
    <br>
    <div>作者：<el-input v-model="article.author"/></div>
    <br>
    <div>发布日期：{{article.authorCreatedTime}} </div>
    <br>
    <div>
        封面：<br>
            <imageShow style="width: 160px; height: 160px;" :value="article.imageId"></imageShow>
        <el-upload
        class="avatar-uploader"
        :action="url"
        :show-file-list="true"
        :on-success = "successHandler"
        :before-upload="beforeAvatarUpload">
        
        <img v-if="imageUrl != ''" :src="imageUrl" class="avatar">
        <el-icon v-else class="el-icon-plus avatar-uploader-icon"> <Plus></Plus> </el-icon>
        </el-upload>
    </div>
    <br>
    <div v-if="article.state || an_state" >状态：<el-switch v-model="article.state"/></div>
    <div v-else>状态：<el-switch v-model="article.state" disabled/></div>
    <br>
    <div>
        <el-button @click="submitData()" text>
            提交  
        </el-button>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref,onBeforeMount } from 'vue';
import Editor from '@tinymce/tinymce-vue';
import createArts from '../api/articleCreate.js';
import { useArticleStore } from '../stores/createarticles.js';
import image from '../api/uploadImages.js';
import getImage from '../api/getImage.js';
import { Operation , Check , Delete , Plus} from '@element-plus/icons-vue'
import getArticle from '../api/getArticleById.js'
import updateArticle from '../api/updateArticle.js'
import imageShow from './imageshow.vue'
import updateArticleAdmin from '../api/updateArticleAdmin'
import isAdmin  from '../api/isAdmin';
import { useRouter } from 'vue-router';
const url = "http://localhost:5173/api/image/upload?token=Bearer " + localStorage.getItem("jwttoken")
    const props = defineProps({
      article:String
    })
    const use = useRouter()
    const imageUrl = ref("")
    const image_id = ref("")
    const drawer = ref(false)
    const imageList = ref([])
    const editorContent = ref('');
    const baseUrl = ref("http://localhost:8080/image?")
    const articles = useArticleStore();
    const article = ref({})
    const an_state = ref(false)
    isAdmin().then((res)=>{
        if(res.status = 200)
        an_state.value= true
    })
    if (props.article != null) 
    if(props.article.trim != "")
      {
        getArticle(props.article).then((res)=>{
          if(res.status ==200)
          {
            editorContent.value = res.data.content;
            articles.id = res.data.id
            article.value = res.data
          }
        })
      }    
    const editorConfig = {
      height: 500,
      menubar: false,
      paste_data_images: true,
      language: 'zh_CN',
      branding: false,
      images_upload_handler: function (blobInfo, success) {
        image({ 'file': blobInfo.blob() }).then(function (res) {
          if (res.status === 200) {
            getImage(res.data).then(function(response){
              if(response.status == 200)
              {
                success(response.data) ;
              }
              else{
                success ("");
              }
            })
            imageList.value.pop(res.data)
          } else {
            this.$message.error('图片上传失败');
            success('');
          }
        });
      },
      plugins: [
        'advlist autolink lists link image charmap print preview anchor',
        'searchreplace visualblocks code fullscreen',
        'insertdatetime media table paste code help wordcount',
      ],
      toolbar:
        'undo redo code image media print | formatselect | bold italic charmap backcolor visualblocks | insertdatetime paste link lists autolink preview | \
        alignleft aligncenter alignright alignjustify indent2em searchreplace | \
        bullist numlist outdent indent table | removeformat | fullscreen anchor | help',
      save_enablewhendirty: false,
    };

    const removeData = () => {
        const dispose = ref({})
        dispose.value = article.value
      if( dispose.value.userId == localStorage.getItem("userId"))
        updateArticle({
            id:dispose.value.id,
            author:dispose.value.author,
            content:dispose.value.content,
            state:false,
            imageId:dispose.value.imageId == null ? ""  : (dispose.value.imageId),
            images:dispose.value.images == null ?  [] : (dispose.value.images),
            title:dispose.value.title,
            type:dispose.value.type,
            userId:dispose.value.userId,
            page:0,
            size:0,
            search:"",
            visits:0,
        }).then((res)=>{
            if(res.status == 200)
            {
                dispose.value = res.data
                ElMessage.success("移除成功")
            }
        })
    }
    const submitData = () => {
      console.log(editorContent.value);
      const data = editorContent.value;
      articles.content = data;
      article.value.content = data;
      if (articles.id == "") 
      createArts({
        author: articles.author,
        title : articles.title,
        content : data ,
        type : articles.type,
        imageId : articles.imageId ,
        images : imageList.value
      }).then(function (res) {
        if(res.status == 200) {
          ElMessage.success("保存成功")
          
        }
      });
      else{
        const dispose = ref({})
        dispose.value = article.value
        if(an_state && article.userId != localStorage.getItem("userId"))
        {
          updateArticleAdmin({
            id:dispose.value.id,
            state:dispose.value.state,
        }).then((res)=>{
            if(res.status == 200)
            {
                dispose.value = res.data
                ElMessage.success("修改成功")
                use.push('/selfInform')
            }
        })
        }
        if( dispose.value.userId == localStorage.getItem("userId"))
        updateArticle({
            id:dispose.value.id,
            author:dispose.value.author,
            content:dispose.value.content,
            state:false,
            imageId:dispose.value.imageId == null ? ""  : (dispose.value.imageId),
            images:dispose.value.images == null ?  [] : (dispose.value.images),
            title:dispose.value.title,
            type:dispose.value.type,
            userId:dispose.value.userId,
            authorCreatedTime:getNowFormatDate(),
            page:0,
            size:0,
            search:"",
            visits:0,
        }).then((res)=>{
            if(res.status == 200)
            {
                dispose.value = res.data
                ElMessage.success("修改成功")
            }
        })
      }
    };

    function getNowFormatDate() {
      let date = new Date(),
        year = date.getFullYear(), 
        month = date.getMonth() + 1, 
        strDate = date.getDate() 
      if (month < 10) month = `0${month}` 
      if (strDate < 10) strDate = `0${strDate}`
    
      return `${year}-${month}-${strDate}`

      }
    function setPanel () {
      drawer.value = true ;
    }
    function successHandler (res,file){ 
        image_id.value =res
        imageUrl.value = URL.createObjectURL(file.raw);
        article.value.imageId = image_id.value
    }
    function beforeAvatarUpload(file) {
        const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
            ElMessage.error('上传头像图片只能是 JPG / PNG 格式!');
            }
            if (!isLt2M) {
            ElMessage.error('上传头像图片大小不能超过 2MB!');
            }


        return isJPG && isLt2M;
    }    

</script>

<style>
  .button {
    height: 5vh;
    width: 5vh;
    margin: 0.5vh;
    
  }

  .button_box {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position:absolute;
    width: 6vh;
    height: 20vh;
    bottom: 25%;
    left: 106%;
  }

</style>
